package flc.ast.utils;

import android.content.Context;
import android.util.Log;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import javax.net.ssl.*;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

public class HttpLatencyTest {
    private static final OkHttpClient client;

    static {
        // 创建 TrustManager，忽略证书验证
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {}

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {}

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };

        // 创建 SSLContext，使用自定义 TrustManager
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            client = new OkHttpClient.Builder()
                    .sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0])
                    .hostnameVerifier((hostname, session) -> true) // 忽略主机名验证
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static long measureLatency(String url) {
        Log.d("HttpLatencyTest", "开始测量时延，URL: " + url);
        Request request = new Request.Builder().url(url).build();

        try {
            long startTime = System.currentTimeMillis();
            Response response = client.newCall(request).execute();
            long endTime = System.currentTimeMillis();

            if (response.isSuccessful()) {
                Log.d("HttpLatencyTest", "请求成功，时延: " + (endTime - startTime) + " ms");
                return endTime - startTime; // 返回时延
            } else {
                Log.d("HttpLatencyTest", "请求失败，状态码: " + response.code());
            }
        } catch (Exception e) {
            Log.e("HttpLatencyTest", "请求异常: " + e.getMessage(), e);
        }
        return -1; // 失败时返回 -1
    }
}